/*
 * @Author: your name
 * @Date: 2020-08-28 11:40:09
 * @LastEditTime: 2020-09-01 16:54:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /express/src/utils/iwencai/analyzer.ts
 */
import fs from 'fs';
import cheerio from 'cheerio';
import { Analyzer } from '../crowller';

interface queryInfoArr {
  title: string;
  url?: string | undefined;
  desc: string;
  type?: string;
}

interface CourseResult {
  time: number;
  data: queryInfoArr[];
}

interface Content {
  [propName: number]: queryInfoArr[];
}

export default class DellAnalyzer implements Analyzer {
  private static instance: DellAnalyzer;

  static getInstance() {
    if (!DellAnalyzer.instance) {
      DellAnalyzer.instance = new DellAnalyzer();
    }
    return DellAnalyzer.instance;
  }

  private getCourseInfo(html: string) {
    const $ = cheerio.load(html);
    const $cnt = $('#hltj_right_hc_query_li_st')
    const queryInfoItems = $cnt.find('.query_info_item')
    const queryInfoArr: queryInfoArr[] = [];
    // queryInfoItems.map((index, element) => {
    //   const wordBox = $(element).find('.word_box');
    //   const itemIcon = $(element).find('.item_icon');
    //   const queryLink = wordBox.find('.query_link');
    //   const queryDesc = wordBox.find('.query_info');
    //   const title = queryLink.eq(0).text();
    //   const url = queryLink.attr('href');
    //   const desc = queryDesc.eq(0).text();
    //   const type = itemIcon.eq(0).text();
    //   queryInfoArr.unshift({ title, url, desc, type });
      // const result = $('#resultWrap')
      // const table = result.find('.static_table')
    // })

    return {
      time: new Date().getTime(),
      data: queryInfoArr
    };
  }

  private generateJsonContent(courseInfo: CourseResult, filePath: string, resetData?: Boolean) {
    let fileContent: Content = {};
    if (fs.existsSync(filePath)) {
      if(!resetData){
        fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
      }
    }
    fileContent[courseInfo.time] = courseInfo.data;
    return fileContent;
  }

  public analyze(html: string, filePath: string, resetData?: Boolean) {
    const courseInfo = this.getCourseInfo(html);
    const fileContent = this.generateJsonContent(courseInfo, filePath, resetData);
    return JSON.stringify(fileContent);
  }

  private constructor() {}
}
